package com.dongdongshop.config;

import com.dongdongshop.api.SellerServiceApi;
import com.dongdongshop.data.Result;
import com.dongdongshop.dto.SellerDTO;
import com.dongdongshop.enums.TokenEnum;
import com.dongdongshop.exception.LoginException;
import com.dongdongshop.model.TbAdmin;
import com.dongdongshop.service.AdminService;
import com.dongdongshop.shiro.LoginToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;

    @Autowired
    private SellerServiceApi sellerServiceApi;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        LoginToken token = (LoginToken) authenticationToken;
        String username = token.getUsername();
        //如果取出tokenEnum
        TokenEnum tokenEnum = token.getTokenEnum();
        if (tokenEnum.equals(TokenEnum.ADMIN)) {
            TbAdmin tbAdmin = adminService.getAdminByName(username);
            if (tbAdmin == null) {
                return null;
            }
            /*账号相同去效验密码*/
            return new SimpleAuthenticationInfo(tbAdmin, tbAdmin.getPwd(), ByteSource.Util.bytes(tbAdmin.getSalt()), tbAdmin.getUname());
        } else if (tokenEnum.equals(TokenEnum.SELLER)) {
            Result<SellerDTO> result = sellerServiceApi.getSellerByName(username);
            SellerDTO sellerDTO = result.getData();
            if (sellerDTO == null){
                    return null;
            }
            if(!"1".equals(sellerDTO.getStatus())){
                throw  new LoginException("账户未审核");
            }
            /*账号相同去效验密码*/
            return new SimpleAuthenticationInfo(sellerDTO, sellerDTO.getPassword(), ByteSource.Util.bytes(sellerDTO.getSalt()), sellerDTO.getName());
        }
        return null;
    }
}
